﻿using System;
using LayerEntity.Hotel;
using LayerEntity.Sistema;
using LayerLogic;
using System.Windows.Forms;
using System.Data;
using DevExpress.XtraEditors;
namespace System2012.Sistema.Documentos
{
    public partial class FrmConfiSeriesComprobantes : DevExpress.XtraEditors.XtraForm
    {
        GUtil util = new GUtil();
        /// <summary>
        /// Indica si estamos editanado o creando uno Nuevo
        /// 0: Nuevo Documento
        /// 1: Editando y Guardando
        /// </summary>
        int operacion = 0;
        /// <summary>
        /// 
        /// </summary>
        DataTable dtbSeries = new DataTable();
        /// <summary>
        /// almacena el index de la tabla al momento de seleccionar un registro
        /// </summary>
        int indexRow;
     //   GUtil util = new GUtil();
        public FrmConfiSeriesComprobantes()
        {
            this.InitializeComponent();
            RecControles(this);
            if (!BGWListarSeries.IsBusy) BGWListarSeries.RunWorkerAsync();
            for (int i = 0; i <     util.GetImpresoras().Count; i++)
            {
                CmbImpresora.Properties.Items.Add(util.GetImpresoras()[i]);
            }
            getEeventos();

        }
        #region EVENTOS
        private void txtSpin(object sender, DevExpress.XtraEditors.Controls.SpinEventArgs e)
        {
            e.Handled = true;
        }

        private void getEeventos()
        {
            this.txtCorelDesde.Spin += new DevExpress.XtraEditors.Controls.SpinEventHandler(this.txtSpin);
            this.txtSerie.Spin += new DevExpress.XtraEditors.Controls.SpinEventHandler(this.txtSpin);
            this.txtCorelDesde.Spin += new DevExpress.XtraEditors.Controls.SpinEventHandler(this.txtSpin);
            this.txtCorrelHasta.Spin += new DevExpress.XtraEditors.Controls.SpinEventHandler(this.txtSpin);
            
        }

        #endregion
        #region Metodos

        private void NuevaSerie()
        {
            operacion = 0;
            this.util.RecControles(this);

        }
        private void GrabarSeries()
        {
            ESeriesDocumento obS = new ESeriesDocumento();
            obS.Id_Tranzaccion = CmbTranzaccion.EditValue.ToString();
            obS.Id_Documento = int.Parse(CmbTipComp.EditValue.ToString());
            obS.Serie = txtSerie.Text; ;
            obS.Numero = int.Parse(txtCorrelativo.Text);
            obS.Impresora = CmbImpresora.Text;
            obS.Plantilla = btnPlantilla.Text;
            obS.Serie_Impresora = txtSerieImpresora.Text; ;
            obS.Id_Sucursal = 1;
            obS.Id_Estado = 1;
            obS.Idusuario = "";
            obS.Desde = int.Parse(txtCorelDesde.Text);
            obS.Hasta = int.Parse(txtCorrelHasta.Text);
            obS.Id_Terminal = 1;
            string res = System2012.SystemUtils.CommonMaintenanceList.MantenimientosSerisDocs(obS, this.operacion == 0 ? EnumOperaciones.Insertar : EnumOperaciones.Actualizar);

            if (res == "0")
            {
                if (!BGWListarSeries.IsBusy) BGWListarSeries.RunWorkerAsync();
                XtraMessageBox.Show(this, "PROCESO EFECTUADO CON EXITO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.None);
            }
            else
            {
                if (res == "-1")
                {
                    XtraMessageBox.Show(this, "INCONSITENCIA INESPERADA AL MOMENTO DE REGISTRAR", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    if (res == "-2")
                    {
                        XtraMessageBox.Show(this, "EL NRO DE SERIE YA SE ENCUENTRA REGISTRADO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        if (res == "-3")
                        {
                            XtraMessageBox.Show(this, "INCONSISTENCIA INESPERADA AL REALIZAR LA ACTUALIZACION", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            if (res == "-4")
                            {
                                XtraMessageBox.Show(this, "SELECCIONE CORRECTAMENTE EL REGISTRO QUE ESTA ACTUALIZANDO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                            }
                        }
                    }
                }
            }

            //   MessageBox.Show(res);
          
        }
        private void Editar(int index)
        {
            CmbEmpresa.EditValue = int.Parse(dtbSeries.Rows[index]["id_empresa"].ToString());
            CmbSucursal.EditValue = int.Parse(dtbSeries.Rows[index]["id_sucursal"].ToString());
            CmbTipComp.EditValue = int.Parse(dtbSeries.Rows[index]["id_documento"].ToString());
            CmbTranzaccion.EditValue = dtbSeries.Rows[index]["id_tranzaccion"].ToString();
            CmbEstado.EditValue = int.Parse(dtbSeries.Rows[index]["id_estado"].ToString());
            txtSerie.Text = dtbSeries.Rows[index]["serie"].ToString();
            txtCorrelativo.Text = dtbSeries.Rows[index]["correlativo"].ToString();
            txtCorelDesde.Text = dtbSeries.Rows[index]["desde"].ToString();
            txtCorrelHasta.Text = dtbSeries.Rows[index]["hasta"].ToString();
            btnPlantilla.Text = dtbSeries.Rows[index]["plantilla"].ToString();
            CmbImpresora.Text = dtbSeries.Rows[index]["impresora"].ToString();
            txtSerieImpresora.Text = dtbSeries.Rows[index]["serie_impresora"].ToString();
            operacion = 1;

        }
        #endregion
        #region Desplazamientos
        private void PresionadoTeclas(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
                
                if (sender == this.txtSerie)
                {
                    this.txtCorrelativo.Focus();
                    this.txtCorrelativo.SelectAll();
                }
                if (sender == this.txtCorrelativo)
                {
                    this.txtCorelDesde.Focus();
                    this.txtCorelDesde.SelectAll();
                }


                if (sender == this.txtCorelDesde)
                {
                    this.txtCorrelHasta.Focus();
                    this.txtCorrelHasta.SelectAll();
                }
                if (sender == this.txtCorrelHasta)
                {
                    this.CmbImpresora.Focus();
                    this.CmbImpresora.SelectAll();
                }
                
                if (sender == this.txtSerieImpresora)
                {
                    this.btnPlantilla.Focus();
                    this.btnPlantilla.SelectAll();
                }
                if (sender == this.btnPlantilla)
                {
                    this.CmbEstado.Focus();
                    this.CmbEstado.SelectAll();
                }
            }
            if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
            {
                if (sender == this.CmbEmpresa)
                {
                    this.CmbSucursal.Focus();
                    this.CmbSucursal.SelectAll();
                }
                if (sender == this.CmbSucursal)
                {
                    this.CmbTerminal.Focus();
                    this.CmbTerminal.SelectAll();
                }
                if (sender == this.CmbTerminal)
                {
                    this.CmbTipComp.Focus();
                    this.CmbTipComp.SelectAll();
                }
                if (sender == this.CmbTipComp)
                {
                    this.CmbTranzaccion.Focus();
                    this.CmbTranzaccion.SelectAll();
                }
                if (sender == this.CmbTranzaccion)
                {
                    this.txtSerie.Focus();
                    this.txtSerie.SelectAll();
                }
                if (sender == this.CmbImpresora)
                {
                    this.txtSerieImpresora.Focus();
                    this.txtSerieImpresora.SelectAll();
                }
            }
            if (e.KeyCode == Keys.Up)
            {
               
                if (sender ==txtSerie )
                {
                    CmbTranzaccion.Focus();
                    CmbTranzaccion.SelectAll();
                }
                if (sender ==txtCorrelativo )
                {
                    txtSerie.Focus();
                    txtSerie.SelectAll();
                }
                if (sender ==txtCorelDesde )
                {
                    txtCorrelativo.Focus();
                    txtCorrelativo.SelectAll();
                }


                if (sender ==txtCorrelHasta )
                {
                    txtCorelDesde.Focus();
                    txtCorelDesde.SelectAll();
                }
                if (sender ==CmbImpresora )
                {
                    txtCorrelHasta.Focus();
                    txtCorrelHasta.SelectAll();
                }
                if (sender ==txtSerieImpresora )
                {
                    CmbImpresora.Focus();
                    CmbImpresora.SelectAll();
                }
                if (sender ==btnPlantilla )
                {
                    txtSerieImpresora.Focus();
                    txtSerieImpresora.SelectAll();
                }
               
            }
            if (e.KeyCode == Keys.Left)
            {
                if (sender == CmbSucursal)
                {
                    this.CmbEmpresa.Focus();
                    this.CmbEmpresa.SelectAll();
                }
                if (sender == CmbTerminal)
                {
                    CmbSucursal.Focus();
                    CmbSucursal.SelectAll();
                }
                if (sender == CmbTipComp)
                {
                    CmbTerminal.Focus();
                    CmbTerminal.SelectAll();
                }
                if (sender == CmbTranzaccion)
                {
                    CmbTipComp.Focus();
                    CmbTipComp.SelectAll();
                }
                if (sender == CmbEstado)
                {
                    btnPlantilla.Focus();
                    btnPlantilla.SelectAll();
                }
            }

        }
        public void RecControles(Control control)
        {
            foreach (Control contHijo in control.Controls)
            {
                if (contHijo.HasChildren)
                {
                    this.RecControles(contHijo);
                }
                contHijo.KeyDown += new KeyEventHandler(PresionadoTeclas);
            }
        }
        #endregion

        #region Validaciones
        private bool Validar()
        {
            bool res = true;
            if (CmbEmpresa.ItemIndex == -1)
            {
                res = false;
                XtraMessageBox.Show(this, "NO HA SELECCIONADO NINGUNA EMPRESA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (CmbSucursal.ItemIndex == -1)
                {
                    res = false;
                    XtraMessageBox.Show(this, "NO HA SELECCIONADO NINGUNA SUCURSAL", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    if (CmbTipComp.ItemIndex == -1)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "NO HA SELECCIONADO NINGUN TIPO DE COMPROBANTE", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        if (CmbTranzaccion.ItemIndex == -1)
                        {
                            res = false;
                            XtraMessageBox.Show(this, "NO HA SELECCIONADO NINGUNA TRANZACCION", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(txtSerie.Text))
                            {
                                res = false;
                                XtraMessageBox.Show(this, "INGRESE EL NRO.SERIE", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(txtCorrelativo.Text))
                                {
                                    res = false;
                                    XtraMessageBox.Show(this, "INGRESE EL INICIO DEL CORRELATIVO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                else
                                {
                                    if (string.IsNullOrEmpty(txtCorelDesde.Text))
                                    {
                                        res = false;
                                        XtraMessageBox.Show(this, "INGRESE EL RANGO DE INICIO DE LA SERIE", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    else
                                    {
                                        if (string.IsNullOrEmpty(txtCorrelHasta.Text))

                                        {
                                            res = false;
                                            XtraMessageBox.Show(this, "INGRESE EL RANGO DE FIN DE LA SERIE", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                        else
                                        {
                                            if (CmbImpresora.SelectedIndex == -1)
                                            {
                                                res = false;
                                                XtraMessageBox.Show(this, "SELECCIONE LA IMPRESORA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            }
                                            else
                                            {
                                                if (CmbTranzaccion.ItemIndex == -1)
                                                {
                                                    res = false;
                                                    XtraMessageBox.Show(this, "SELECCIONE EL ESTADO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return res;
        }
        #endregion
        private void BGWEmpresa_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetEmpresas();
        }

        private void BGWEmpresa_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            this.CmbEmpresa.Properties.DataSource = e.Result;
        }

        private void BGWSucursal_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            EHotel obj = new EHotel();
            if (CmbEmpresa.EditValue != null)
            {
                obj.Condicion = "where id_empresa=" + this.CmbEmpresa.EditValue.ToString();
                e.Result = System2012.SystemUtils.RecordManagerCommonList.GetListaSucursal(obj);
            }
        }

        private void BGWSucursal_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            this.CmbSucursal.Properties.DataSource = e.Result;
            if (!BGWTipDoc.IsBusy) BGWTipDoc.RunWorkerAsync();
        }

        private void CmbSucursal_EditValueChanged(object sender, EventArgs e)
        {
          
        }

        private void CmbEmpresa_EditValueChanged(object sender, EventArgs e)
        {
            if (!BGWSucursal.IsBusy) BGWSucursal.RunWorkerAsync();
        }

        private void BGWTipDoc_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetDocument(2);
        }

        private void BGWTipDoc_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            this.CmbTipComp.Properties.DataSource = e.Result;
            if (!BGWTranzaccion.IsBusy) BGWTranzaccion.RunWorkerAsync();
        }

        private void BGWTranzaccion_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetTranzaccion();
        }

        private void BGWTranzaccion_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            CmbTranzaccion.Properties.DataSource = e.Result;
            if (!BGWEstado.IsBusy) BGWEstado.RunWorkerAsync();
        }

        private void BGWEstado_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetEstados();
        }

        private void BGWEstado_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            CmbEstado.Properties.DataSource = e.Result;
            //if (!BGWListarSeries.IsBusy) BGWListarSeries.RunWorkerAsync();
        }

        private void btnGrabar_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (Validar())
            {
                GrabarSeries();
            }
        }

        private void BGWListarSeries_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            ESistema obj = new ESistema();
            obj.Condicion = "";
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetListaSeriesDocumento(obj);
        }

        private void BGWListarSeries_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            dtbSeries = (DataTable)e.Result;
            gridControl2.DataSource = e.Result;
            if (!BGWEmpresa.IsBusy) BGWEmpresa.RunWorkerAsync();
        }

        private void FrmConfiSeriesComprobantes_Load(object sender, EventArgs e)
        {

        }

        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            this.indexRow = e.FocusedRowHandle;
        }

        private void gridControl2_DoubleClick(object sender, EventArgs e)
        {
            
        }

        private void gridView2_DoubleClick(object sender, EventArgs e)
        {
            Editar(indexRow);
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
         
            NuevaSerie();
        }

        private void FrmConfiSeriesComprobantes_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5 || (e.Control && e.KeyCode == Keys.S))
            {
                if (Validar())
                {
                    GrabarSeries();
                }
            }
            if (e.KeyCode == Keys.Escape)
            {
                if (XtraMessageBox.Show(this, "Está seguro que desea Salir \n" +
                        "Confirmación Requerida ?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    this.Close();
                }
            }
            if (e.Control && e.KeyCode == Keys.N)
            {
                NuevaSerie();
               
            }
        }

        private void layoutControlItem1_DoubleClick(object sender, EventArgs e)
        {
            
        }

        private void txtSerie_Leave(object sender, EventArgs e)
        {
            string codigo = this.txtSerie.Text;
            while (codigo.Length < 4)
            {
                codigo = string.Format("0{0}", codigo);
            }
            this.txtSerie.Text = codigo;
        }

        private void txtSerie_Enter(object sender, EventArgs e)
        {
            if (this.txtSerie.Text.Length > 0)
            {
                int codigo = int.Parse(this.txtSerie.Text);
                this.txtSerie.Text = string.Format("{0}", codigo);
            }
        }
    }
}